import { AddUserFnc, EditUserFnc, GetUserInfoFnc } from '@/services/users';
import type { ProFormInstance } from '@ant-design/pro-components';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import { message } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { itemType } from './type';

const AddEdit = ({
  isModalOpen,
  openBox,
  openType,
  actionRef,
  openID,
}: itemType) => {
  const formRef: any = useRef<ProFormInstance>();
  // 用于做比较的form
  const [formObj, setFormObj] = useState({});

  // 打开编辑盒子
  const init = async () => {
    if (openID !== '' && openType !== '') {
      const res = await GetUserInfoFnc(parseInt(openID));
      if (res.meta.status === 200) {
        formRef.current.setFieldsValue({
          id: res.data.id,
          username: res.data.username,
          email: res.data.email,
          mobile: res.data.mobile,
        });
        setFormObj({
          username: res.data.username,
          email: res.data.email,
          mobile: res.data.mobile,
        });
      }
    }
  };
  useEffect(() => {
    init();
  }, [openID]);

  // 邮箱和电话 验证逻辑
  const checkEmailorMobile = (reg: any, value: string, text: string) => {
    if (value === undefined || reg.test(value) === false) {
      return Promise.reject(text);
    } else {
      return Promise.resolve();
    }
  };

  // valida 邮箱和电话
  const validateEmail = (rules: any, value: string) => {
    if (rules.field === 'email') {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      return checkEmailorMobile(regEmail, value, '请输入合法邮箱');
    } else {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      return checkEmailorMobile(regMobile, value, '请输入合法的手机号');
    }
  };

  // 公共消息
  const publicMsg = (msg: string) => {
    message.open({
      type: 'success',
      content: msg,
      duration: 1.5,
      onClose: () => {
        openBox(false);
        actionRef.current?.reload();
        formRef.current.setFieldsValue({
          username: '',
          password: '',
          email: '',
          mobile: '',
        });
      },
    });
  };

  // 添加用户 修改用户
  const onFinish = async (info: {
    username: string;
    password: string;
    email: string;
    mobile: string;
  }) => {
    if (openType === 'add') {
      const res = await AddUserFnc(info);
      if (res.meta.status === 201) {
        // 添加
        publicMsg(res.meta.msg);
        actionRef.current?.reload();
      }
    } else {
      if (JSON.stringify(formObj) === JSON.stringify(info)) {
        openBox(false);
      } else {
        const res = await EditUserFnc(parseInt(openID), info);
        publicMsg(res.meta.msg);
      }
    }
  };

  return (
    <ModalForm
      title={openType === 'add' ? '添加用户' : '修改用户'}
      formRef={formRef}
      width={500}
      layout="horizontal"
      labelCol={{ span: 4 }}
      open={isModalOpen}
      onFinish={async (val: {
        username: string;
        password: string;
        email: string;
        mobile: string;
      }) => onFinish(val)}
      modalProps={{ onCancel: () => openBox(false) }}
    >
      <ProFormText
        name="username"
        label="用户名"
        rules={[
          { required: true, message: '请输入用户名' },
          { min: 3, max: 10, message: '长度在3-10个字符' },
        ]}
      />
      {openType === 'add' ? (
        <ProFormText.Password
          name="password"
          label="密码"
          rules={[
            { required: true, message: '请输入密码' },
            { min: 3, max: 10, message: '长度在3-10个字符' },
          ]}
        />
      ) : (
        ''
      )}
      <ProFormText
        name="email"
        label="邮箱"
        rules={[
          {
            required: true,
            validator: (rule, value) => validateEmail(rule, value),
          },
        ]}
      />
      <ProFormText
        name="mobile"
        label="手机号"
        rules={[
          {
            required: true,
            validator: (rule, value) => validateEmail(rule, value),
          },
        ]}
      />
    </ModalForm>
  );
};

export default AddEdit;
